package com.sita.cfmoto.interact.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.edmodo.cropper.CropImageView;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.sita.cfmoto.R;
import com.sita.cfmoto.event.ReleaseDynamicEvent;
import com.sita.cfmoto.rest.RestClient;
import com.sita.cfmoto.rest.model.ReleaseDynamicParams;
import com.sita.cfmoto.rest.model.RestResponse;
import com.sita.cfmoto.support.Constants;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.utils.BitmapUtils;
import com.sita.cfmoto.utils.PersistUtils;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import pl.aprilapps.easyphotopicker.DefaultCallback;
import pl.aprilapps.easyphotopicker.EasyImage;
import pl.tajchert.nammu.Nammu;
import pl.tajchert.nammu.PermissionCallback;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;

public class ReleaseDynamicActivity extends AppCompatActivity {
    @Bind(R.id.pop_parent)
    RelativeLayout popParent;
    @Bind(R.id.dynamic_pic)
    ImageView dynamicPic;
    @Bind(R.id.dynamic_public_txt)
    TextView dynamicVisible;
    @Bind(R.id.dynamic_location_txt)
    TextView dynamicLocation;
    @Bind(R.id.dynamic_content_edit)
    EditText dynamicContentEdit;
    private int LOCATION = 3;
    private boolean showAddress = false;
    private boolean showPublic = true;
    private String mAddress = null;
    private Double lat = null;
    private Double lng = null;
    private String topicId;

    @OnClick(R.id.pop_parent)
    void clickPopParent(){
        hideKeyBoard();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release_dynamic);
        ButterKnife.bind(this);
        topicId = getIntent().getStringExtra("topicId");
        initLocation();
        initPublic();
    }

    void initPublic() {
        showPublic(true);
    }

    private void initLocation() {
        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
        String mCity = location.getCity();
        dynamicLocation.setText(mCity);
        mAddress = mCity;
        lat = location.getLatitude();
        lng = location.getLongitude();
    }

    void showPublic(boolean show) {
        if (show) {
            showPublic = true;
            dynamicVisible.setText(getString(R.string.dynamic_public));
        } else {
            showPublic = false;
            dynamicVisible.setText(getString(R.string.dynamic_not_public));
        }
    }

    @OnClick(R.id.dynamic_pic)
    void onClickDynamicPic() {
        hideKeyBoard();
        openPhotoPopup();
    }

    @OnClick(R.id.dynamic_public_layout)
    void onClickDynamicPublic() {
        hideKeyBoard();
        openPublicPopup();
    }

    @OnClick(R.id.dynamic_location_layout)
    void onClickDynamicLocation() {
        Intent intent = new Intent();
        intent.setClass(this, LocationPoiActivity.class);
        startActivityForResult(intent, LOCATION);
    }

    @OnClick(R.id.cancel)
    void onClickCancel() {
        finish();
    }

    @OnClick(R.id.finish)
    void onClickFinish() {
        //先判断是否全部选了
        if (TextUtils.isEmpty(dynamicContentEdit.getText()) ||
                dynamicPic.getDrawable() == null ||
                TextUtils.isEmpty(dynamicVisible.getText()) ||
                TextUtils.isEmpty(dynamicLocation.getText())) {
            Toast.makeText(this, getString(R.string.dynamic_miss_information), Toast.LENGTH_SHORT).show();
        } else {
            releaseDynamic();
        }
    }

    private void openPhotoPopup() {
        PopupWindow pop = new PopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.item_dynamic_pic_pop, null);

        LinearLayout popupLayout = (LinearLayout) view.findViewById(R.id.popup_layout);

        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setContentView(view);
        pop.showAtLocation(popParent, Gravity.BOTTOM, 0, 0);
        pop.update();

        RelativeLayout itemLayout = (RelativeLayout) view.findViewById(R.id.item_layout);
        Button btCam = (Button) view
                .findViewById(R.id.item_popupwindows_camera);
        Button btPhoto = (Button) view
                .findViewById(R.id.item_popupwindows_Photo);
        Button btCancel = (Button) view
                .findViewById(R.id.item_popupwindows_cancel);
        itemLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
        btCam.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // take photo
                clickTakePhoto();
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
        btPhoto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                clickPickFromGallery();
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
        btCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
    }

    protected void clickTakePhoto() {
        /**Permission check only required if saving pictures to root of sdcard*/
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            EasyImage.openCamera(this, 0);
            getIntent().putExtra(Constants.BUNDLE_APP_STATE, Constants.AppState.IN_CAMERA_PHOTO.name());
        } else {
            Nammu.askForPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, new PermissionCallback() {
                @Override
                public void permissionGranted() {
                    EasyImage.openCamera(ReleaseDynamicActivity.this, 0);
                    getIntent().putExtra(Constants.BUNDLE_APP_STATE, Constants.AppState.IN_CAMERA_PHOTO.name());
                }

                @Override
                public void permissionRefused() {

                }
            });
        }
    }

    protected void clickPickFromGallery() {
        /** Some devices such as Samsungs which have their own gallery app require write permission. Testing is advised! */
        getIntent().putExtra(Constants.BUNDLE_APP_STATE, Constants.AppState.IN_CAMERA_PHOTO.name());
        EasyImage.openGallery(this, 1);
    }

    private void openPublicPopup() {
        PopupWindow pop = new PopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.item_dynamic_public_pop, null);

        LinearLayout popupLayout = (LinearLayout) view.findViewById(R.id.popup_layout);

        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setContentView(view);
        pop.showAtLocation(popParent, Gravity.BOTTOM, 0, 0);
        pop.update();

        RelativeLayout itemLayout = (RelativeLayout) view.findViewById(R.id.item_layout);
        Button btPublic = (Button) view
                .findViewById(R.id.item_popupwindows_public);
        Button btUnPublic = (Button) view
                .findViewById(R.id.item_popupwindows_unpublic);
        Button btCancel = (Button) view
                .findViewById(R.id.item_popupwindows_cancel);
        itemLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
        btPublic.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showPublic(true);
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
        btUnPublic.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showPublic(false);
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
        btCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LOCATION && resultCode == RESULT_OK) {
            String str = data.getStringExtra("myLocation");
            if (str != null) {
                showAddress = true;
                mAddress = str;
                lat = data.getDoubleExtra("lat", 0);
                lng = data.getDoubleExtra("lng", 0);
                dynamicLocation.setText(str);
            } else {
                showAddress = false;
                mAddress = "";
                lat = 0d;
                lng = 0d;
                dynamicLocation.setText(getString(R.string.dynamic_no_location));
            }
        }
        EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
            @Override
            public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
                //Some error handling
            }

            @Override
            public void onImagePicked(File imageFile, EasyImage.ImageSource source, int type) {
                //Handle the image

                showWindow(imageFile);
//                Picasso.with(GlobalContext.getGlobalContext())
//                        .load(imageFile).centerInside()
//                        .fit()
//                        .into(dynamicPic);
//
//                dynamicPic.setTag(imageFile.getAbsolutePath());
            }

            @Override
            public void onCanceled(EasyImage.ImageSource source, int type) {
                //Cancel handling, you might wanna remove taken photo if it was canceled
                if (source == EasyImage.ImageSource.CAMERA) {
                    File photoFile = EasyImage.lastlyTakenButCanceledPhoto(ReleaseDynamicActivity.this);
                    if (photoFile != null) photoFile.delete();
                }
            }
        });
    }

    private void showWindow(File imageFile) {
        PopupWindow popupWindow = new PopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.window_image_cropper, null);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setContentView(view);
        popupWindow.showAtLocation(popParent, Gravity.BOTTOM, 0, 0);
        popupWindow.update();
        CropImageView cropImageView = (CropImageView) view.findViewById(R.id.cropImageView);
        cropImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        File mFile = new File(imageFile.getAbsolutePath());
        if (mFile.exists()) {//若该文件存在
            Bitmap bm = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
            bm = BitmapUtils.getAdaptiveBitmap(bm);
            cropImageView.setImageBitmap(bm);
        }
        cropImageView.setFixedAspectRatio(true);
        cropImageView.setGuidelines(CropImageView.DEFAULT_GUIDELINES);
        cropImageView.setAspectRatio(1, 1);
        view.findViewById(R.id.crop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取裁剪成的图片
                Bitmap croppedImage = cropImageView.getCroppedImage();
                dynamicPic.setImageBitmap(croppedImage);
                popupWindow.dismiss();
            }
        });
    }

    private void releaseDynamic() {
        final MaterialDialog uploadDialog = new MaterialDialog.
                Builder(this).
                content("正在发布...").
                progress(true, 5000).
                build();
        uploadDialog.show();
        TypedFile avatar = null;
        File headImageFile = dynamicImgSaveToLocal();
//      avatar = new TypedFile("image/jpg", new File(editAcct.getAvatar()));
        avatar = (headImageFile.equals("")) ? null : new TypedFile("image/jpg", headImageFile);
        ReleaseDynamicParams params = new ReleaseDynamicParams();
        params.authorId = PersistUtils.getUsers().get(0).getAccountId();
        params.content = String.valueOf(dynamicContentEdit.getText());
        params.visible = dynamicVisible.getText().equals("公开") ? 1 : 0;
        params.address = mAddress;
        params.lat = lat;
        params.lng = lng;
        params.source = 0;
        params.topicId = topicId;
        String reqStr = RestClient.getGson().toJson(params);
        TypedString typedString = new TypedString(reqStr);
//
        RestClient.getRestService().releaseDynamic(avatar, typedString, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                if (response.getStatus() == 200 && restResponse.mErrorCode.equals("0")) {
//                    Gson gson = JsonUtils.getGson();
//                    String s = gson.toJson(restResponse.mData);
//                    Account account = gson.fromJson(s, Account.class);
//                    updateStorage(account.getAccountId(), account.getNickName(), account.getMobile(), account.getAvatar());

                    uploadDialog.dismiss();

                } else {
                    uploadDialog.dismiss();
                }
                if (topicId == null) {
                    EventBus.getDefault().post(new ReleaseDynamicEvent(0));
                } else {
                    EventBus.getDefault().post(new ReleaseDynamicEvent(1));
                }
                finish();
//            finishActivity(MySettings.UPDATE_PROFILE);
            }

            @Override
            public void failure(RetrofitError error) {
                uploadDialog.dismiss();
                showErrorMessage();
            }
        });


    }

    private void showErrorMessage() {
        final NormalDialog dialog = new NormalDialog(this);
        dialog.style(NormalDialog.STYLE_ONE)
                .titleLineColor(getResources().getColor(R.color.blue))
                .titleTextSize(20)
                .title(getString(R.string.warm_tips))
                .contentTextColor(getResources().getColor(R.color.black))
                .contentGravity(Gravity.CENTER)
                .content(getString(R.string.error_release_dynamic_fail))
                .btnNum(1)
                .show();
        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dialog.dismiss();
            }
        });
    }

    private File dynamicImgSaveToLocal() {
        String IMAGE_FILE_NAME = "temp_header.jpg";
        File activeImageFile = BitmapUtils.saveBmpFile(((BitmapDrawable) dynamicPic.getDrawable()).getBitmap(), IMAGE_FILE_NAME);
        return activeImageFile;
    }

    private void hideKeyBoard(){
        InputMethodManager imm = (InputMethodManager) this.getSystemService(ReleaseDynamicActivity.this.INPUT_METHOD_SERVICE);
        dynamicContentEdit.setCursorVisible(false);//失去光标
        imm.hideSoftInputFromWindow(dynamicContentEdit.getWindowToken(), 0);
    }
}
